import { Editor } from 'amis-editor';
import React, { useState } from 'react';
import '../scss/style.scss';
import 'amis/lib/themes/default.css';
import 'amis/sdk/iconfont.css';
import 'amis-editor/dist/style.css';
import '@fortawesome/fontawesome-free/css/all.css';
import '@fortawesome/fontawesome-free/css/v4-shims.css';
import '../editor/DisabledEditorPlugin';
import '@/editor/DisabledEditorPlugin';
import { useLocation } from 'umi';
import {
  MessageActionEnums,
  MessageFrom,
  ReqMessageModel,
  RespMessageEnums,
  RespMessageModel,
} from '@/pages/model/MessageModel';
import { message } from 'antd';

let schemaJson: any = null;

export default () => {

  const location = useLocation();
  // @ts-ignore
  const pageId = location.query.pageId;
  // @ts-ignore
  const pageType = location.query.pageType;
  // @ts-ignore
  const pageTitle = location.query.pageTitle;

  function change(val: any) {
    console.log('change value=', val);
    schemaJson = val;
    localStorage.setItem('jsonSchema' + pageId + pageType, JSON.stringify(val));
  }

  /**
   * 保存页面配置
   */
  function save() {
    if (pageId && pageType) {
      const msg: ReqMessageModel = {
        from: MessageFrom.CHILD,
        data: schemaJson,
        action: MessageActionEnums.SAVE,
        pageId: pageId,
        pageType: pageType,
      };
      console.log('schemaJson====', msg, pageId, pageType);
      sendMsg2Parent(msg);
    } else {
      message.warn('参数不完整');
    }
  }

//初始化数据
  function initSchema() {
    schemaJson = JSON.parse(localStorage.getItem('jsonSchema' + pageId + pageType) as string);
  }

  const [isMobile, setMobile] = useState(false);
  const [isPreview, setPreview] = useState(false);
  /**
   * 是否以移动模式预览
   * @param flag
   */
  const changeMode = (flag: boolean) => {
    setMobile(flag);
  };
  /**
   * 预览
   * @param flag
   */
  const preview = (flag: boolean) => setPreview(flag);

  function exit() {
    const msg: ReqMessageModel = {
      from: MessageFrom.CHILD,
      action: MessageActionEnums.EXIT,
    };
    console.log('退出编辑器');
    sendMsg2Parent(msg);
  }

  initSchema();

  /**
   * 从父窗体的消息
   */
  window.onmessage = function(e) {
    const resp: RespMessageModel = JSON.parse(e.data);
    if (resp.from === MessageFrom.PARENT) {
      console.log('接受消息来到至父页的消息：', e.data);
      switch (resp.action) {
        case MessageActionEnums.INIT:
          console.log('初始化数据');
          localStorage.setItem('jsonSchema' + pageId + pageType, JSON.stringify(resp.data));
          initSchema();
          break;
        case MessageActionEnums.TIPS:
          if (resp.type == RespMessageEnums.ERROR) {
            message.info('操作成功');
          } else {
            message.error('操作失败');
          }
          break;
      }
    }
  };


  return (
    <div className='Editor-main'>
      <div className='Editor-header'>
        <div className='Editor-title'>可视化编辑器-【{pageTitle}】</div>
        <div className='Editor-view-mode-group-container'>
          <div className='Editor-view-mode-group'>
            <div
              className={`Editor-view-mode-btn ${
                !isMobile ? 'is-active' : ''
              }`}
              onClick={() => {
                changeMode(false);
              }}
            > PC模式
            </div>
            <div
              className={`Editor-view-mode-btn ${
                isMobile ? 'is-active' : ''
              }`}
              onClick={() => {
                changeMode(true);
              }}
            > 移动模式
            </div>
          </div>
        </div>
        <div className='Editor-header-actions'>
          <div
            className={`header-action-btn margin-left-space ${
              isPreview ? 'primary' : ''
            }`}
            onClick={() => {
              preview(!isPreview);
            }}
          >
            {isPreview ? '编辑' : '预览'}
          </div>
          {!isPreview && (
            <div className={`header-action-btn save-btn`} onClick={save}>
              保存
            </div>
          )}
          {!isPreview && (
            <div className={`header-action-btn exit-btn`} onClick={exit}>
              退出
            </div>
          )}
        </div>
      </div>
      <div className='Editor-inner'>
        <Editor
          theme={'cxd'}
          className='is-fixed'
          isMobile={isMobile}
          showCustomRenderersPanel={true}
          preview={isPreview}
          autoFocus={true}
          onChange={change} value={schemaJson} />
      </div>
    </div>
  );

};


/**
 * 发送消息给父窗体
 */
function sendMsg2Parent(msg: ReqMessageModel) {
  console.log('给父窗体发送消息');
  window.parent.postMessage(JSON.stringify(msg), location.origin);
}

